package com.dm.webCrawler.framework.auth.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dm.webCrawler.framework.auth.mode.LoginUser;
import com.dm.webCrawler.framework.config.properties.TokenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dm.webCrawler.common.exception.CustomException;
import com.dm.webCrawler.framework.auth.AuthCacheUtil;
import com.dm.webCrawler.framework.auth.AuthUtils;

/**
 * 防止重复提交拦截器
 * 
 * @author ruoyi
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter
{
	@Autowired
	private AuthCacheUtil authCacheUtil;
	@Autowired
	private HttpSession session;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    	if(request.getMethod().equals("OPTIONS")) {
    		return true;
    	}
    	String token = request.getHeader(TokenProperties.getHeader());
    	if(token==null) {
    		token=request.getParameter(TokenProperties.getHeader());
    		if(token==null) {
    			throw new CustomException("token验证失败，请提交认证信息！",401);
    		}
    	}
    	LoginUser user = authCacheUtil.getUserBytoken(token, true);
    	if(user==null) {
    		throw new CustomException("token验证失败，认证信息可能过期！",403);
    	}
    	AuthUtils.setCurrUser(session, user);
    	return true;
    }

}
